import React, { Component } from 'react';
import { connect } from 'dva';
import { Card, Button, Tabs, Switch, Icon, Input } from 'antd';
import _ from 'lodash';
import mapOnLoad from '../../utils/map';
import { randomStr } from '../../utils/util';
require('./detailGrid.less');
const TabPane = Tabs.TabPane;

const styles = {
  detail: {
    // width:'100%',
    minHeight: '380px',
    overflow: 'hidden'
  },
  if: {
        border: 'none',
        height: '331px',
        width: '100%',
    }
};

const geocoder = null;
let Marker = null;
let LngLat = null;

class DeviceMap extends Component {
    constructor(props) {
        super(props);
        this.state = {
            value: [113.32058, 23.162637]
        };
        this.key = randomStr();
        // mapOnLoad(this.initComponent);
    }

    // initComponent =() => {
    //     if (window.AMap.service !== undefined) {
    //         geocoder ? null : window.AMap.service('AMap.Geocoder', () => geocoder = new window.AMap.Geocoder({}));
    //     }
    // }

    componentDidMount() {
        mapOnLoad(this.init);
    }

    componentWillReceiveProps(nextProps) {
		let { detailData } = nextProps.device;
		if (nextProps.device.detailData !== this.props.device.detailData) {
			detailData = nextProps.device.detailData || {};
            this.setState({ value: [nextProps.device.detailData.longitude, nextProps.device.detailData.latitude] });
		}
	}

    componentDidUpdate(prevProps, prevState) {
        const { value } = this.state;
		if (!_.isEqual(prevState.value, value) && this.inited) {
			if (!!value[0]) {
                this.map = new window.AMap.Map(this.key, {
                    resizeEnable: true,
                    zoom: 12,
                    center: value
                });
                this.addMarker({ lnglat: value });
            } else {
                this.addMarker({ lnglat: [113.32058, 23.162637] });
            }
		}
	}

    addMarker = e => {
		if (!this.inited) return;
		if (this.marker) this.map.remove(this.marker);
		this.marker = new window.AMap.Marker({
            icon: 'http://webapi.amap.com/theme/v1.3/markers/n/mark_b.png',
			position: e.lnglat,
            map: this.map
		});
	}

    init = () => {
        const { value } = this.state;
        this.inited = true;
        Marker = window.AMap.Marker;
		LngLat = window.AMap.LngLat;
        // mapOnLoad(this.initComponent);
        this.map = new window.AMap.Map(this.key, {
            resizeEnable: true,
            zoom: 12,
            center: value && value.length ? value : [113.32058, 23.162637]
        });
	}

    render() {
        return (
            <Card title="设备位置" style={styles.detail}>
                <div id={this.key} style={styles.if}></div>
            </Card>
        );
    }
}

DeviceMap.propTypes = {
};

export default connect(({ device }) => ({ device }))(DeviceMap);

